package com.xsq;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.POSD.controllers.PrinterController;
import com.alibaba.fastjson.JSON;
import com.common.utils.CommonUtils;
import com.common.utils.LogUtils;
import com.xsq.activity.ConsumeBackActivity;
import com.xsq.activity.ConsumeMngActivity;
import com.xsq.activity.ConsumeSrchActivity;
import com.xsq.activity.DeviceSetActivity;
import com.xsq.activity.GuideActivity;
import com.xsq.bo.Card;
import com.xsq.util.DeviceUtils;
import com.xsq.util.HttpInterface;
import com.xsq.util.M1Card;
import com.xsq.util.MD5Util;
import com.xsq.util.NetWorkUtils;
import com.xsq.util.PrintUtils;
import com.xsq.util.ServerUtils;
import com.xsq.util.SignUtils;
import com.xsq.util.SignUtilsImpl;
import com.xsq.util.StringFormatUtils;


@SuppressLint({ "SetJavaScriptEnabled", "HandlerLeak", "SimpleDateFormat" })
public class PosMainActivity extends BaseActivity   {
	
	private NfcAdapter nfcAdapter;
	private PendingIntent pendingIntent;

	//流水号
	private static int flow_counter = 1;
	//回首页
	private static final int GO_HOME = 1000;
	//显示卡用户信息
	private static final int SRCH_CARDINFO = 1001;
	//显示卡用户信息
	private static final int SHOW_CARDINFO = 1002;
	//显示消费结构信息
	private static final int POS_CONSUME_RESULT = 1007;
	// app升级
	private static final int DO_UPDATE = 1008;
	//POS机器系统设置
	private static final int POS_SYS_SET = 2000;
	//POS机器消费管理
	private static final int POS_CONSUME_MNG = 2001;
	//主页--》消费纠错
	private static final int POS_CONSUME_BACK = 20015;
	//主页--》当日消费查询
	private static final int POS_CONSUME_SRCH = 20011;
	
	private ProgressBar mProgress; // 下载进度条控件
	private  final int DOWNLOADING = 3001; // 表示正在下载
	private  final int DOWNLOADED = 3002; // 下载完毕
	private  final int DOWNLOAD_FAILED = 3003; // 下载失败
	private int progress; // 下载进度
	private boolean cancelFlag = false; // 取消下载标志位
	private String updateDescription = "请更新到最新版本"; // 更新内容描述信息
	private boolean forceUpdate = false; // 是否强制更新

	private  double clientVersion;
	private  double serverVersion;
	private SignUtils signUtils = new SignUtilsImpl();
	

	
	private PrinterController printerController = null;
	
	
	
	
	
	@Override
	public void onCreate(Bundle savedState) {
		super.onCreate(savedState);
	
		
		
		//初始化缓存
		preferences = getSharedPreferences(Constant.CACHE_XSQ_POS, MODE_PRIVATE);
		editor = preferences.edit();
		
		//获取设备序列号
		String deviceId = "";
		TelephonyManager tm = (TelephonyManager) getApplication().getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId();
		if(imei==null){
			deviceId = DeviceUtils.getUniqueId(getApplicationContext());
		}else{
			deviceId = DeviceUtils.getDeviceID()+imei;
		}
		editor.putString(Constant.CACHE_DEVICEID,deviceId);
		editor.commit();
		
		if (getServerInfo().equals("") || getPosNo().equals("") || getWinNo().equals("")) {
			//到引导页面去设置系统信息
			Intent intent = new Intent(this, GuideActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
			return;
		}
		
		setContentView(R.layout.main);
		
		
		// 透明导航栏，就是下面三个虚拟按钮
		initStyle();
		
		//初始化接口
		serverUtils = new ServerUtils(preferences, editor);
		hi = new HttpInterface(serverUtils);
		//检测是否有网络
		boolean wifiA = NetWorkUtils.isNetworkConnected(getApplicationContext());
		if (!wifiA) {
			Toast.makeText(this, "当前网络不可用", Toast.LENGTH_LONG).show();
			this.finish();
			return;
		}
		//初始化NFC
		initnfc();
		//获取客户端版本
		clientVersion = getVersionCode(this);
	
		
		
		
		
		if (null == printerController) {
			printerController = PrinterController.getInstance(this);
		}
		int flag = printerController.PrinterController_Open();
		if (flag == 0) {
			//Toast.makeText(this, "connect_Success", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "打印机无法连接,请重试", Toast.LENGTH_SHORT).show();
			
		}
		
		Constant.threadPoolExecutor.execute(new Runnable() {

			public void run() {

				String serverInfo = getServerInfo();
				String posno = getPosNo();
				String winno = getWinNo();
				
				if(serverInfo==null || serverInfo.equals("")){
					//提醒配置上位机
					sendMessage("0",null);
					
				}else if(posno.equals("") || winno.equals("")){
					//提醒配置系统信息
					sendMessage("1",null);
					
				}else{
					
					Map<String, Object> dbPosInfo = hi.validatePosParam(posno, getDeviceId(),winno);	
					if (String.valueOf(dbPosInfo.get("is_success")).equals("0")) {
						// POS机的本地信息过期或者现在已经不正确了
						//Toast.makeText(getApplicationContext(), "POS系统信息过期或失效,请重新配置",Toast.LENGTH_LONG).show();
						sendMessage("1",1000L);
					}else{
						//更新一些信息
						editor.putString(Constant.CACHE_WINNAME, String.valueOf(dbPosInfo.get("winname")));
						editor.putString(Constant.CACHE_MERCHANT, String.valueOf(dbPosInfo.get("merchantname")));
						editor.putString(Constant.CACHE_XFXX, String.valueOf(dbPosInfo.get("xfxe")));
						editor.commit();
						
						// 参数正确,判断时间是否相差很大
						String curTime = dbPosInfo.get("curTime")==null? null: String.valueOf(dbPosInfo.get("curTime"));
						if(curTime!=null){
							
							try {
							
								//服务器时间
								Date d1 = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(curTime);
								//设备时间
								double d2 = System.currentTimeMillis();
								//相差的秒
								double dd = Math.abs(d2-d1.getTime())/1000;
								if(dd>2*3600){
									//相差2小时以上
									pageShowMsg("POS机系统时间与服务器时间相差2小时以上，请检查!",5000L);
									
								}
								
							} catch (ParseException e) {
								
							}
							
						}
					}

					boolean needCheck = false;
					String update_alert = getUpdateAlert();
					if (update_alert != null && !update_alert.equals("")) {
						// 已提醒,判断是否是今天
						String today = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
						if (update_alert.equals(today)) {
							needCheck = false;
						} else {
							needCheck = true;
						}
					} else {
						needCheck = true;
					}
					double server_version = 0;
					if (needCheck) {
						server_version = Double.parseDouble(hi.getLatestVersion());
					}

					if (server_version > clientVersion) {
						// showNoticeDialog();
						Message msg = new Message();
						msg.what = DO_UPDATE;
						Bundle data = new Bundle();
						data.putString("server_version", server_version + "");
						msg.setData(data);
						mHandler.sendMessage(msg);

					} else {
						// 删除升级文件
						try {
							File apkFile = new File(Constant.saveFileName);
							if (!apkFile.exists()) {
								
							} else {
								apkFile.delete();
							}
						} catch (Exception e) {
							
						}
					}
					
					Map<String,Object> otherInfo = new HashMap<String, Object>();
					MyTimeTask timeTask = MyTimeTask.getInstance(hi, posno, otherInfo);
					timeTask.editor = editor;
					timeTask.preferences = preferences;
					
					otherInfo.put("version", clientVersion);
					
					
					otherInfo.put("cardMode", getCardType());//读卡模式
					otherInfo.put("printCode", getPrintCodeVersion());//打印编码
					otherInfo.put("pwdType", getConsumePwdMode());//密码验证模式
					otherInfo.put("printMode", getConsumePrintMode());//打印模式
					
					if(!timeTask.isDoing()){
						timeTask.startupTask();
						LogUtils.info("开启定时任务...");
					}else{
						LogUtils.info("已经在执行了...");
					}
					
				}
				
				
			}
		});
		
		

		myWebView = (WebView) findViewById(R.id.webview);

		WebSettings webSettings = myWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(false); // 支持缩放
		webSettings.setBuiltInZoomControls(false); // 显示放大缩小
		webSettings.setDefaultTextEncodingName("utf-8");
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 解决缓存问题
		myWebView.addJavascriptInterface(new PageControl(this), "appControl");
		myWebView.setWebViewClient(new MyWebViewClient());
		myWebView.setWebChromeClient(new MyWebChromeClient());
		myWebView.loadUrl(URLConstant.PAGE_INDEX);
		myWebView.requestFocus();

	}
	
	/**
	 * 跳转到系统设置页面
	 * @param setType  0=配置上位机IP 1=配置逻辑号窗口号
	 */
	public void sendMessage(String setType,Long delayMillis){
		
		Message message = new Message();
		message.what = POS_SYS_SET;
		Bundle bundle = new Bundle();
		bundle.putString("setType", setType);
		message.setData(bundle);
		if(delayMillis==null){
			mHandler.sendMessage(message);
		}else{
			mHandler.sendMessageDelayed(message,1000);
		}
		
	}
	
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GO_HOME:
				loadHome();
				break;
			case POS_SYS_SET:
				loadSysPage(msg);
				break;
			case POS_CONSUME_MNG:
				loadConsumePage();
				break;
			case POS_CONSUME_BACK:
				loadConsumeBackPage();
				break;	
			case POS_CONSUME_SRCH:
				loadConsumeSrchPage();
				break;	
				
			case SRCH_CARDINFO:
				loadCardInfo(msg.getData().getString("cardsno"),msg.getData().getString("cardno"));
				break;
			case SHOW_CARDINFO:
				showCardInfo(msg);
				break;
			case POS_CONSUME_RESULT:
				showConsumeResult(msg.getData().getString("rs"),msg.getData().getString("consumetime"),msg.getData().getString("money"),getPrintTitle());
				break;		
				
				
			case DOWNLOADING:
				mProgress.setProgress(progress);
				break;
			case DOWNLOADED:
				if (alertDialog2 != null) {
					alertDialog2.dismiss();
				}
				cancelFlag = true;
				installAPK();
				break;
			case DOWNLOAD_FAILED:
				Toast.makeText(PosMainActivity.this, "网络断开，请稍候再试", Toast.LENGTH_LONG).show();
				break;
			case DO_UPDATE:
				Bundle data = msg.getData();
				serverVersion = Double.parseDouble(data.getString("server_version"));
				showNoticeDialog();
				break;
			}
		}
	};

	
	
	
	
	//根据卡号加载用户信息
	public void loadCardInfo(final String cardsno,final String cardno){
		
		
		
		show_loading("正在读取用户信息...");
		
		Constant.threadPoolExecutor.execute(new Runnable() {
			
			@Override
			public void run() {
				
				Map<String,Object> map = null;
				
				try {
					map = hi.getUserInfo(cardsno,cardno);
					
					if(String.valueOf(map.get("is_success")).equals("1")){
						Integer curMoney = Integer.parseInt(String.valueOf(map.get("balance")));
						BigDecimal c_money = new BigDecimal(curMoney);
						c_money = c_money.divide(new BigDecimal(100));
						
						map.put("curMoney", StringFormatUtils.getFormatJe(c_money.toString()));
					
					}
				} catch (Exception e) {
					map = new HashMap<String, Object>();
					map.put("is_success", "-2");
					map.put("error_msg", "读取卡用户信息失败,请重试...");
				}
				
				//获取用户信息后,执行页面js,显示卡用户信息
				Message message = new Message();
				message.what = SHOW_CARDINFO;
				Bundle bundle = new Bundle();
				bundle.putString("rs", JSON.toJSONString(map));
				message.setData(bundle);
				mHandler.sendMessage(message);
			}
		});
		
		
	}
	
	
	private void showCardInfo(Message message){
		
		String rs = message.getData().getString("rs");
		String call = "javascript:showCardUserInfo('"+rs+"');";
		
		myWebView.loadUrl(call);
		hide_loading();
	}
	
	
	private void showConsumeResult(String rs,String consumetime,String money,final String printTitle){
		
		Map<String,Object> map = JSON.parseObject(rs, Map.class);
		
		Map<String,Object> pageResult = new HashMap<String, Object>();

		if(String.valueOf(map.get("is_success")).equals("-1")){
			
			pageResult.put("is_success", "0");
			pageResult.put("msg", "无法连到可用的服务器,请联系管理员");
		}else if(String.valueOf(map.get("is_success")).equals("0")){
			pageResult.put("is_success", "0");
			pageResult.put("msg", String.valueOf(map.get("error_msg")));
			
		}else{
			pageResult.put("is_success", "1");
			//验签,确定是否真正的交易完成
			String mac = String.valueOf(map.get("mac"));
			String flowcode = String.valueOf(map.get("flowcode"));
			String rs_consumetime = String.valueOf(map.get("consumetime"));
			
			if(!consumetime.equals(rs_consumetime)){
				pageResult.put("is_success", "0");
				pageResult.put("msg", "系统异常错误【数据不完整】");
				
			}else{
				
				boolean validRs = signUtils.verify(flowcode+rs_consumetime, mac, Constant.publicKey, Constant.SIGNATURE_ALGORITHM);
				if(validRs){
					
					
					//验签通过,打印发票并页面显示交易结果
					final int printFlag = Integer.parseInt(getConsumePrintMode());
					final Map<String,Object> consumeInfo = map;
					final String winname = getWinName();
					final String printcode = getPrintCodeVersion();
					if(printFlag>0){
						Constant.threadPoolExecutor.execute(new Runnable() {
							public void run() {
								//打印
								for(int i=0;i<printFlag;i++){
									PrintUtils.printConsumeInfo(printerController,printTitle, consumeInfo, winname, printcode);
								}
								
							}
						});
					}
					
					//此处可加语音提示.........................
				
					
					
					pageResult.put("is_success", "1");
					pageResult.put("msg", "交易成功");
					pageResult.put("jyMoney", StringFormatUtils.getFormatJe(""+Double.parseDouble(money)/100));//交易金额
					pageResult.put("kyMoney", map.get("kyMoney")==null? "":StringFormatUtils.getFormatJe(""+Double.parseDouble(String.valueOf(map.get("kyMoney")))/100));//可用金额
					
				}else{
					pageResult.put("is_success", "0");
					pageResult.put("msg", "系统异常错误【数据不完整或者传输中被修改】");
				}
			}
		}
		
		//页面显示
		String content = JSON.toJSONString(pageResult);
		String call = "javascript:showConsumeResult('"+content+"');";
		
		myWebView.loadUrl(call);
		
		hide_loading();
		
	}
	

	
	/**
	 * 去首页
	 */
	private void loadHome() {
		Intent intent = new Intent(this, DeviceSetActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}

	/**
	 * 跳转到系统设置页面
	 */
	private void loadSysPage(Message msg) {
		Intent intent = new Intent(this, DeviceSetActivity.class);
		Bundle bundle = msg.getData();
		intent.putExtra("setType", bundle.getString("setType"));
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	/**
	 * 跳转到消费管理页面
	 */
	private void loadConsumePage() {
		Intent intent = new Intent(this, ConsumeMngActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	
	/**
	 * 跳转到消费回退页面
	 */
	private void loadConsumeBackPage() {
		Intent intent = new Intent(this, ConsumeBackActivity.class);
		intent.putExtra("fromPage", Constant.PAGE_FLAG_MAIN_INDEX);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	
	/**
	 * 跳转到当日消费页面
	 */
	private void loadConsumeSrchPage() {
		Intent intent = new Intent(this, ConsumeSrchActivity.class);
		intent.putExtra("fromPage", Constant.PAGE_FLAG_MAIN_INDEX);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}
	
	
	
	/**
	 * NFC设置后，王者归来
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100) {
			nfcAdapter = NfcAdapter.getDefaultAdapter(this);
			if (!nfcAdapter.isEnabled()) {
				Toast.makeText(this, R.string.nfc_not_open, Toast.LENGTH_SHORT).show();
			}
		}
	}

	@SuppressLint("NewApi")
	private void initnfc() {

		nfcAdapter = NfcAdapter.getDefaultAdapter(PosMainActivity.this);
		if (nfcAdapter == null) {
			Toast.makeText(this, R.string.nfc_device_not_support, Toast.LENGTH_SHORT).show();
			finish();
		}
		if (!nfcAdapter.isEnabled()) {
			AlertDialog dialog = new AlertDialog.Builder(this).setMessage(getString(R.string.nfc_not_open_go_open))
					.setPositiveButton(getString(R.string.yes), new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent("android.settings.NFC_SETTINGS");
							startActivityForResult(intent, 100);
						}
					}).create();
			dialog.show();
		}
		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,getClass()), 0);
		//pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (nfcAdapter != null) {
			nfcAdapter.enableForegroundDispatch(this, pendingIntent, null,null);
		}
	}


	@Override
	public void onNewIntent(Intent intent) {

		Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		byte[] myNFCID = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
		
		if (tag == null){
			Toast.makeText(getApplicationContext(), "tag为空", Toast.LENGTH_LONG).show();
			return;
		}
		String[] techList = tag.getTechList();
		String card_mode = getCardType();
		if(card_mode.equals("0")){
			//ID卡模式
			String cardsno = bytesToHexString(myNFCID);
			//进行卡片信息查询	
			Message message = new Message();
			message.what = SRCH_CARDINFO;
			Bundle bundle = new Bundle();
			bundle.putString("cardsno",cardsno);
			bundle.putString("cardno","");
			message.setData(bundle);
			mHandler.sendMessage(message);
			
			
		}else if(card_mode.equals("1")){
			//M1卡模式
			boolean m1flag = false;
			if (techList != null && techList.length > 0) {
				for(int i = 0; i < techList.length; i++){
					if(techList[i].contains("MifareClassic")){
						m1flag = true;
						break;
					}
				}
			}
			if(!m1flag){
				Toast.makeText(getApplicationContext(), "请把卡片移开，重新靠读卡位置刷卡", Toast.LENGTH_LONG).show();
				return;
			}
			
			
			if (techList != null && techList.length > 0) {
				a: for (int i = 0; i < techList.length; i++) {
					if (techList[i].contains("MifareClassic")) {
						
						Card.mMifareClassic = MifareClassic.get(tag);
						boolean autha = false;
						int sector = 12;
						int blockIndex = 48;
						try {
							Card.mMifareClassic.connect();
							autha = Card.mMifareClassic.authenticateSectorWithKeyA(sector, new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 });
							if (autha) {
								byte[] data = Card.mMifareClassic.readBlock(blockIndex);
								//读卡，并进行卡片查询
								String cardsno = bytesToHexString(myNFCID);
								String cardno = M1Card.getCardno(data);
								
								//进行卡片信息查询	
								Message message = new Message();
								message.what = SRCH_CARDINFO;
								Bundle bundle = new Bundle();
								bundle.putString("cardsno",cardsno);
								bundle.putString("cardno",cardno);
								message.setData(bundle);
								mHandler.sendMessage(message);
								
							} else {
								//卡片非鑫三强卡片,或者卡片密钥被改过
								Toast.makeText(getApplicationContext(), "卡片非本系统卡片", Toast.LENGTH_LONG).show();
								
								
							}

						} catch (Exception e1) {
							
							e1.printStackTrace();
						}
						break a;
					}
				}
			}
			
			
		}else{
			Toast.makeText(getApplicationContext(), "暂不支持当前读卡模式", Toast.LENGTH_LONG).show();
			return;
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (nfcAdapter != null) {
			nfcAdapter.disableForegroundDispatch(this);
		}
	}

	private class PageControl {

		private Context mContext;
		PageControl(Context c) {
			mContext = c;
		}
		

		/**
		 * 验证系统密码
		 * @param pwd
		 * @return
		 */
		@JavascriptInterface
		public String validateSysSetPwd(String pwd){
			try{
				LogUtils.info("当前密码-->"+getSysAdmin());
				if(pwd.equals(getSysAdmin())){
					return "1";
				}
				return "0";
			}catch(Exception e){
				return "-1";
			}
		}
		
		@JavascriptInterface
		public String validateOperPwd(String pwd){
			try{
				if(pwd.equals(getOperAdmin())){
					return "1";
				}
				return "0";
			}catch(Exception e){
				return "-1";
			}
		}
		
		/**
		 * 系统设置
		 * @param pwd
		 */
		@JavascriptInterface
		public void goToSysSet(String pwd) {
			String privFlag = "0";
			if(pwd.equals(getSysAdmin())){
				privFlag = "1";
			}
			Message message = new Message();
			message.what = POS_SYS_SET;
			Bundle bundle = new Bundle();
			bundle.putString("privFlag", privFlag);
			message.setData(bundle);
			mHandler.sendMessage(message);
		}
		
		
		/**
		 * 消费管理
		 */
		@JavascriptInterface
		public void goToConsumeSet() {
			Message message = new Message();
			message.what = POS_CONSUME_MNG;
			Bundle bundle = new Bundle();
			bundle.putString("test", "test");
			message.setData(bundle);
			mHandler.sendMessage(message);
		}
		
		
		/**
		 * 跳转到查询当日流水页面
		 */
		@JavascriptInterface
		public void toSrchTodayFlow() {
			Message message = new Message();
			message.what = POS_CONSUME_SRCH;
			Bundle bundle = new Bundle();
			bundle.putString("test", "test");
			message.setData(bundle);
			mHandler.sendMessage(message);
		}
		
		/**
		 * 交易回退
		 */
		@JavascriptInterface
		public void toConsumeBackFromIndex() {
			
			Message message = new Message();
			message.what = POS_CONSUME_BACK;
			Bundle bundle = new Bundle();
			bundle.putString("test", "test");
			message.setData(bundle);
			mHandler.sendMessage(message);
		}
		
		
		/**
		 * 交易请求
		 * @param usercode
		 * @param cardsno
		 * @param cardno
		 * @param pwd
		 * @param money
		 * @return
		 */
		@JavascriptInterface
		public String  doConsumeRequest(final String cardsno,final String cardno,final String pwd,final String money) {
			

			show_loading("正在提交交易数据...");
			
			Constant.threadPoolExecutor.execute(new Runnable() {
				@Override
				public void run() {
					
				
					
					Map<String,Object> map = null;
					String consumetime = "";
					int amount = 0;
					try{	
						consumetime = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
						String flowid = getPosNo()+consumetime+(flow_counter++);
						String consumepwd = "";
						
						BigDecimal bg = new BigDecimal(money);
						amount = bg.multiply(new BigDecimal(100)).intValue();
						
						if(Integer.parseInt(getXfxx())>0 && Integer.parseInt(getXfxx())< amount){
							if(getConsumePwdMode().equals("0")){
								 consumepwd = MD5Util.encodeByMD5(32, pwd).toUpperCase();
							}else if(getConsumePwdMode().equals("1")){
								//明文
								consumepwd = pwd;
							}else{
								//默认密文
								consumepwd = MD5Util.encodeByMD5(32, pwd).toUpperCase();
							}
						}else{
							consumepwd = "";
						}
						
						final String posno = getPosNo();
						
						map = hi.doConsume(flowid, posno, cardsno, cardno, amount+"", consumetime, consumepwd);
		
						LogUtils.info("-->"+map);
						
						
						
					}catch(Exception e){
						//e.printStackTrace();
						map = new HashMap<String,Object>();
						map.put("is_success", "0");
						map.put("msg", "系统异常");
					}
					
					
				
					Message message = new Message();
					message.what = POS_CONSUME_RESULT;
					Bundle bundle = new Bundle();
					bundle.putString("rs", JSON.toJSONString(map));
					bundle.putString("consumetime", consumetime);
					bundle.putString("money", amount+"");
					message.setData(bundle);
					mHandler.sendMessage(message);
					
					
					
				}
			});
			
			return "1";	
		}
		
		
		
		
		/**
		 * 
		 * @param type all=全部 1=上位机  2=系统参数  3=其他设置
		 * @return
		 */
		@JavascriptInterface
		public String srchSysInfo(String type) {

			Map<String, Object> info = new HashMap<String, Object>();
			try {

				if (type.equals("4") || type.equals("all")) {

					info.put("sysTitle", getSysTitle());
					info.put("xfxe", getXfxx());
				} else {
					info.put("is_success", "0");
				}

				info.put("is_success", "1");
			} catch (Exception e) {
				e.printStackTrace();
				info.put("is_success", "0");
			}
			return JSON.toJSONString(info);
		}
		
		
		
		@JavascriptInterface
		public String srcQuatoInfo() {

			Map<String, Object> info = new HashMap<String, Object>();
			try {

				info.put("quatoMode", getSFQuatoConsume());
				info.put("quatoMoney", getQuatoConsumeMoney());

				info.put("is_success", "1");
			} catch (Exception e) {
				e.printStackTrace();
				info.put("is_success", "0");
			}
			return JSON.toJSONString(info);
		}
		
	}

	
	
	private class MyWebChromeClient extends WebChromeClient {

		public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
			AlertDialog.Builder b2 = new AlertDialog.Builder(PosMainActivity.this).setTitle("提示：").setMessage(message)
					.setPositiveButton("ok", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					});
			b2.setCancelable(false);
			b2.create();
			b2.show();
			return true;
		}
	
	}
	
	private class MyWebViewClient extends WebViewClient {
		/**
		 * 如果希望点击链接由自己处理，而不是新开Android的系统browser中响应该链接。
		 * 给WebView添加一个事件监听对象（WebViewClient)并重写其中的一些方法：
		 * shouldOverrideUrlLoading：对网页中超链接按钮的响应。当按下某个连接时
		 * WebViewClient会调用这个方法，并传递参数：按下的url。比如当webview内嵌
		 * 网页的某个数字被点击时，它会自动认为这是一个电话请求，会传递url：tel:123,
		 * 如果你不希望如此可通过重写shouldOverrideUrlLoading函数解决
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// 当开启新的页面的时候用webview来进行处理而不是用系统自带的浏览器处理
			// 互联网用：webView.loadUrl("http://www.google.com");
			// 本地文件用：webView.loadUrl("file:///android_asset/XX.html"); 本地文件存放
			view.loadUrl(url);
			return true;
		}

		/**
		 * 载入页面完成的事件
		 **/
		@Override
		public void onPageFinished(WebView view, String url) {
			// 获取网页内容
			// view.loadUrl("javascript:window.local_obj.showSource"+
			// "('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
			super.onPageFinished(view, url);
		}

		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			// 这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。

			Toast.makeText(getApplicationContext(), "加载失败,请联系管理员", Toast.LENGTH_LONG).show();
		}
	}

	/*************************************** 更新相关 *************************************************/

	/** 显示更新对话框 */
	public void showNoticeDialog() {
		// 如果版本最新，则不需要更新
		if (serverVersion <= clientVersion) {
			return;
		}
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("发现新版本 ：" + serverVersion);
		dialog.setMessage(updateDescription);

		dialog.setPositiveButton("现在更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {

				arg0.dismiss();
				showDownloadDialog();
			}
		});
		// 是否强制更新
		if (forceUpdate == false) {
			dialog.setNegativeButton("下次更新", new OnClickListener() {
				public void onClick(DialogInterface arg0, int arg1) {

					editor.putString(Constant.CACHE_UPDATE_ALERT, (new SimpleDateFormat("yyyy-MM-dd")).format(new Date()));
					editor.commit();
					arg0.dismiss();
				}
			});
		}
		alertDialog1 = dialog.create();
		alertDialog1.setCancelable(true);
		alertDialog1.show();
	}

	/** 显示进度条对话框 */
	public void showDownloadDialog() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("正在更新");
		final LayoutInflater inflater = LayoutInflater.from(this);
		View v = inflater.inflate(R.layout.softupdate_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		dialog.setView(v);
		// 如果是强制更新，则不显示取消按钮
		if (forceUpdate == false) {
			dialog.setNegativeButton("取消", new OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {

					arg0.dismiss();
					cancelFlag = false;
				}
			});
		}
		alertDialog2 = dialog.create();
		alertDialog2.setCancelable(false);
		alertDialog2.show();

		// 下载apk
		downloadAPK();
	}

	/** 下载apk的线程 */
	public void downloadAPK() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					
					List<String> serverList = serverUtils.getAllAviableServers();
					
					URL url = new URL("http://${SERVER}/EduOpenPlatform/posApp/appDownload.do".replace("${SERVER}", serverList.get(0)));
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.connect();

					int length = conn.getContentLength();
					InputStream is = conn.getInputStream();

					File file = new File(Constant.savePath);
					if (!file.exists()) {
						file.mkdirs();
					}
					String apkFile = Constant.saveFileName;
					File ApkFile = new File(apkFile);
					FileOutputStream fos = new FileOutputStream(ApkFile);

					int count = 0;
					byte buf[] = new byte[1024];

					do {
						int numread = is.read(buf);
						count += numread;
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOADING);
						if (numread <= 0) {
							// 下载完成通知安装
							mHandler.sendEmptyMessage(DOWNLOADED);
							break;
						}
						fos.write(buf, 0, numread);
					} while (!cancelFlag); // 点击取消就停止下载.

					fos.close();
					is.close();
				} catch (Exception e) {
					mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
					e.printStackTrace();
				}
			}
		}).start();
	}

	/** 下载完成后自动安装apk */
	public void installAPK() {
		File apkFile = new File(Constant.saveFileName);
		if (!apkFile.exists()) {
			return;
		}

		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
		startActivity(intent);
	}

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return
	 */
	private double getVersionCode(Context context) {
		double versionCode = 0;
		try {
			// 获取软件版本号，对应AndroidManifest.xml下android:versionCode
			versionCode = context.getPackageManager().getPackageInfo(packageName, 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}
	
	 public static int counter = 0;
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
         if(keyCode == KeyEvent.KEYCODE_BACK){
        	
        	 	counter++;
				new Handler().postDelayed(new Runnable() {
					public void run() {
						counter--;
					}
				}, 3 * 1000);
				if (counter > 1) {
					 CommonUtils.Exit(this);  
				} else {
					Toast.makeText(PosMainActivity.this, "再次点击退出应用", Toast.LENGTH_SHORT).show();
				}

        	 
        	 
             return true;
         }
         return super.onKeyDown(keyCode, event);
     }


}